package com.sunlands.zlcx.usercenter.service.status;

import com.sunlands.zlcx.usercenter.constant.LearningStatus;
import com.sunlands.zlcx.usercenter.constant.RedisKeyConst;
import com.sunlands.zlcx.usercenter.domain.LearnContentDO;
import com.sunlands.zlcx.usercenter.domain.UsersTargetRelationDO;
import com.sunlands.zlcx.usercenter.exception.UserTimeLearningException;
import com.sunlands.zlcx.usercenter.exception.UserNotLearningException;
import com.sunlands.zlcx.usercenter.service.status.common.AbstractStudyStatus;
import com.sunlands.zlcx.usercenter.util.BeanPropertiesUtil;
import com.sunlands.zlcx.usercenter.vo.UsersStudyInfoVO;
import com.sunlands.zlcx.usercenter.vo.UsersVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author gaoyanfeng
 * @create 2019-04-28 9:50
 **/
@Component
@Slf4j
public class OrdernaryLearnPause extends AbstractStudyStatus implements BeanPropertiesUtil {
    @Override
    public void handle(UsersStudyInfoVO usersStudyInfoVO, UsersTargetRelationDO usersTargetRelationDO) {
        Long userId = usersTargetRelationDO.getUserId();
        usersStudyInfoVO.setPauseTime(new Date());
        checkPausePeriod(usersStudyInfoVO.getPauseTime(), userId);
        usersService.updateStatus(userId, LearningStatus.LEARN_TIMING_PAUSE.getCode(), null, null, null);
        if (Objects.nonNull(usersStudyInfoVO.getContentId())) {
            LearnContentDO contentDO = usersLearnService.findOne(usersStudyInfoVO.getContentId());
            contentDO.setStatus(LearningStatus.LEARN_TIMING_PAUSE.getCode());
            usersLearnService.update(contentDO);
        }
        String pauseKey = RedisKeyConst.getPauseLearnTimeByUserid(userId);
        redisTemplate.opsForList().leftPush(pauseKey, usersStudyInfoVO.getPauseTime());

    }

    private void checkPausePeriod(Date pauseTime, Long userId) {
        if (null == pauseTime) {
            throw new IllegalArgumentException("暂停时间不能为空");
        }
        UsersVO usersVO = usersService.findOne(userId);
        if (!LearningStatus.canPause(usersVO.getStatus())) {
            throw new UserNotLearningException("当前用户不在学习中 userId = " + userId + "status = " + usersVO.getStatus());
        }
        Date lastLearningEndTime = usersLearnTimingRepository.getLastLearningEndTime(userId);
        if (null != lastLearningEndTime && pauseTime.getTime() < lastLearningEndTime.getTime()) {
            throw new UserTimeLearningException("暂停时间小于上次学习结束时间 userId = " + userId + "status = " + usersVO.getStatus());
        }
    }
}
